﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Agile.Engine.View;
using System.Collections;
using Agile.Engine;
using Agile.Engine.Data;
using System.Data;

namespace Fis.Win.Rules
{
    public class BillListViewProvider : ClientViewProvider
    {
        public string Master { get; set; }
        public string Detail { get; set; }

        public override Hashtable InitializeViewModel(Hashtable args)
        {
            return ExecuteQuery(args);
        }

        public override bool ExecuteUpdateXtra(Hashtable viewModel)
        {
            var filter = viewModel["SyncFilter"].ToString();
            var param = Fis.Win.Utils.AppSession.CreateServiceParamter(viewModel);
            param["Action"] = "Sync";

            var mstData = DataContext.DefaultModel.QueryTable(Master, filter);
            if (mstData.Rows.Count < 1)
                return true;

            var dtlData = DataContext.DefaultModel.QueryTable(Detail
                , " FVCHID IN ( SELECT SID FROM TBILLMASTER WHERE 1=1 AND" + filter + ")");

            AccountTreatViewProvider acc = Fis.Win.Utils.AppSession.GetViewProvider("AccountTreatViewProvider") as AccountTreatViewProvider;
            Hashtable bill = new Hashtable();
            bill["BillDetailTB"] = dtlData;
            bill["BillMasterTB"] = mstData;

            var check = acc.BillCheck(bill);
            if (!check["State"].Equals(0))
            {
                var seq = (from dd in dtlData.Select(string.Format("SID in ({0})", check["ErrorBillDetailID"]))
                           select dd["FVCHID"].ToString()).ToArray();

                var sid = (from dd in mstData.Select(string.Format("SID in ('{0}')", string.Join("','", seq)))
                           select dd["FSEQUENCE"].ToString()).ToArray();

                View.Message = string.Format("凭证序号[{0}]信息不完整，请修改后重新上传", string.Join("],[", sid));
                return false;
            }

            param["master"] = Agile.Engine.Utils.ZipUtils.ZipDataTable(mstData);
            param["detail"] = Agile.Engine.Utils.ZipUtils.ZipDataTable(dtlData);

            var exec = InvokeService(param);

            if (exec)
            {
                if (ServiceProcess.Result.ContainsKey("master"))
                {
                    var m = Agile.Engine.Utils.ZipUtils.UnZipDataTable(ServiceProcess.Result["master"].ToString());
                    DataAccess mda = new DataAccess() { Context = DataContext, TableName = Master };
                    mda.Update(m.Select());
                }
            }

            View.Message = ServiceProcess.Message;
            return exec;
        }

        public DataTable InitPrintPreview(string repx, Hashtable param)
        {
            var xml = ObjectContext.GetResource("SqlResource");
            var sql = xml.Format("bill_report", param["filter0"], param["filter1"]);
            var dataTable = DataContext.DefaultModel.QueryTable(System.Data.CommandType.Text, "Report", sql);
            System.Collections.Generic.Dictionary<object, List<DataRow>> cache = new Dictionary<object, List<DataRow>>();
            foreach (var data in dataTable.AsEnumerable())
            {
                var count = dataTable.Compute("Count(FNO)", string.Format("FNO={0} AND ROWNUM='{1}'", data["FNO"], data["ROWNUM"]));
                int length = int.Parse(count.ToString());
                if (length < 5 && !cache.ContainsKey(data["ROWNUM"]))
                {
                    System.Collections.Generic.List<System.Data.DataRow> list = new System.Collections.Generic.List<System.Data.DataRow>();
                    for (var i = length; i < 5; i++)
                    {
                        var newData = dataTable.NewRow();
                        newData.ItemArray = data.ItemArray;
                        newData["FEXPLANATION"] = string.Empty;
                        newData["FDETAILNAME"] = string.Empty;
                        newData["FDEBITAMOUNT"] = DBNull.Value;
                        newData["FCREDITAMOUNT"] = DBNull.Value;
                        list.Add(newData);
                    }
                    cache[data["ROWNUM"]] = list;
                }
            }

            foreach (var entry in cache.Values)
            {
                foreach (var row in entry)
                    dataTable.Rows.Add(row);
            }

            dataTable.DefaultView.Sort = "FENTERDATE,FNO,ROWNUM";
            return dataTable;
        }
        public void ShowPrintPreview(string repx, DataTable param)
        {
            Fis.Win.Utils.ReportFactory.CreateReport(repx, param);
        }

        public override Hashtable ExecuteQuery(object param)
        {
            Hashtable model = param as Hashtable;
            var filter1 = model["filter1"].ToString();

            var sql = ObjectContext.GetResource("SqlResource").Format("billQuery", model["filter0"]
                , string.IsNullOrEmpty(filter1) ? string.Empty : ObjectContext.GetResource("SqlResource").Format("billSubQuery", filter1));
            model["viewData"] = DataContext.DefaultModel.QueryTable(System.Data.CommandType.Text, DataTableName, sql);
            return model;
        }

        public override bool ExecuteUpdate(Hashtable viewModel)
        {
            if (viewModel["FSYNC"].Equals(1))
            {
                var param = Fis.Win.Utils.AppSession.CreateServiceParamter(null);
                param["Action"] = "Delete";
                param["SID"] = viewModel["SID"];

                var exec = InvokeService(param);

                View.Message = ServiceProcess.Message;
                if (exec)
                {
                    DataContext.DefaultModel.ExecuteTransaction(
                    () =>
                    {
                        DataContext.DefaultModel.Delete(Master, string.Format("SID='{0}'", viewModel["SID"]));
                        DataContext.DefaultModel.Delete(Detail, string.Format("FVCHID='{0}'", viewModel["SID"]));
                    });
                }

                return exec;

            }
            else
            {
                DataContext.DefaultModel.ExecuteTransaction(
                    () =>
                    {
                        DataContext.DefaultModel.Delete(Master, string.Format("SID='{0}'", viewModel["SID"]));
                        DataContext.DefaultModel.Delete(Detail, string.Format("FVCHID='{0}'", viewModel["SID"]));
                    });
            }
            return true;
        }
    }
}
